package io.web.usercenter.aspect;

import io.web.usercenter.common.ErrorCode;
import io.web.usercenter.exception.BusinessException;
import io.web.usercenter.model.domain.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static io.web.usercenter.contant.UserConstant.ADMIN_ROLE;
import static io.web.usercenter.contant.UserConstant.USER_LOGIN_STATE;

/**
 * HasPermissionAspect.
 *
 * @date 2023-05-18
 */
@Aspect
@Component
public class HasPermissionAspect {

    @Around("@annotation(permission)")
    public Object around(ProceedingJoinPoint joinPoint, HasPermission permission) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return joinPoint.proceed();
    }
}
